// 接口访问记录
import { CallHandler, ExecutionContext, Inject, Injectable, Logger, NestInterceptor } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { FastifyReply, FastifyRequest } from 'fastify';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Observable, tap } from 'rxjs';

@Injectable()
export class InvokeRecordInterceptor implements NestInterceptor {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
    private readonly jwtService: JwtService,
  ) { }
  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest<FastifyRequest>();
    const response = context.switchToHttp().getResponse<FastifyReply>();

    const userAgent = request.headers['user-agent'];

    const { ip, method, url } = request;

    this.logger.debug(
      `${method} ${url} ${ip} ${userAgent}: ${context.getClass().name} ${context.getHandler().name} invoked...`,
    );

    const authorization = request.headers.authorization;
    if (authorization) {
      const verityUser = this.jwtService.verify(authorization);
      this.logger.debug(`user: ${verityUser?.userId}, ${verityUser?.username}`);
    }

    const now = Date.now();

    return next.handle().pipe(
      tap((res) => {
        this.logger.debug(
          `${method} ${url} ${ip} ${userAgent}: ${response.statusCode}: ${Date.now() - now}ms`,
        );
        // this.logger.debug(`Response: ${JSON.stringify(res)}`);
      }),
    );
  }
}

